
package com.wondertek.poms.core.manager;

import cn.hutool.core.convert.Convert;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.core.service.IContentBlackService;
import com.wondertek.poms.core.service.IContentWhiteService;
import com.wondertek.poms.core.service.IPcPrdInfoRuleService;
import com.wondertek.poms.core.service.IPrdContService;
import com.wondertek.poms.core.service.IPrdInfoService;
import com.wondertek.poms.core.utils.OutHttpUtil;
import com.wondertek.poms.dao.po.Content;
import com.wondertek.poms.dao.po.ContentBlack;
import com.wondertek.poms.dao.po.ContentWhite;
import com.wondertek.poms.dao.po.PrdCont;
import com.wondertek.poms.dao.po.PrdInfo;
import com.wondertek.poms.dao.repo.IPrdContDao;
import com.wondertek.poms.dao.repo.IPrdInfoDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class InPrdInfoManager {

    @Autowired
    public IPcPrdInfoRuleService prdInfoRuleService;
    @Resource
    private OutHttpUtil outHttpUtil;
    @Autowired
    private ChargeManager chargeManager;
    @Autowired
    private IPrdContService prdContService;
    @Autowired
    private EsManager esManager;
    @Autowired
    private PrdInfoRuleManager proInfoRuleManage;
    @Autowired
    private IPrdInfoService prdInfoService;
    @Autowired
    public IContentBlackService contentBlackService;
    @Autowired
    public IContentWhiteService contentWhiteService;
    @Autowired
    private InPrdInfoManager inPrdInfoManager;
    @Autowired
    private NotifyBcManager notifyBcManager;
    @Autowired
    private IPrdContDao prdContDao;
    @Autowired
    private IPrdInfoDao prdInfoDao;



    /**
     * 入包流程
     * @param c
     * @param prdInfo
     */
    public void inPrdInfoProcess(Content c, PrdInfo prdInfo){
        PrdCont cipi = initPrdCont(c,prdInfo);
        chargeManager.chargePrdCont(cipi, prdInfo, c);
        chargeManager.matchEquityId(cipi, prdInfo, c);
        prdContService.save(cipi);
        esManager.process(cipi);
        prepareNotify(prdInfo, c, cipi);
        //todo 混编通知
        //mixedHttpUtils.mixedCharge(cipi, prdInfo);
    }

    /**
     * 入包前的判断
     * @param content
     * @param prdInfo
     * @return
     */
    public String inPrdInfoRule(Content content,PrdInfo prdInfo, List<PrdCont> prdContList){
        String msg="";

        if(content.getStatus() == 2){
            msg = "中断入包，该内容已删除，不能入包！";
            log.info(msg);
            return msg;
        }else if("13".equals(content.getFormType()) || "7".equals(content.getFormType())){
            msg = "中断入包，该内容不能单独操作！";
            log.info(msg);
            return msg;
        }

        if(prdInfo == null || prdInfo.getIsPublish() ==1){
            msg = "中断入包，该商品包不存在或未发布！";
            log.info(msg);
            return msg;
        }

        if(prdInfo.getProductInfoPackageId() != null){
            //二级产品规则匹配
            Boolean flag = prdContService.passProductRule(content, prdInfo.getProductInfoPackageId());
            if(flag){
                msg = "中断入包，该内容不符合该商品包对应二级产品的二级产品规则！";
                log.info(msg);
                return msg;
            }
            //查询同二级产品下是否存在同媒资节目
            prdContList = prdContService.getPrdContByMmsId(content.getAssetId(), prdInfo.getProductInfoPackageId());
            if(prdContList != null && prdContList.size() >0){
                msg = "中断入包，该二级产品已存在同媒资节目！";
                log.info(msg);
                return msg;
            }
            //黑名单匹配
            if(filterBlack(content.getContentId(), Convert.toStr(prdInfo.getPrdInfoId()))){
                msg = "中断入包，黑名单存在相关记录！";
                log.info(msg);
                return msg;
            }
            if(filterWhiteByPip(content.getContentId(),prdInfo.getProductInfoPackageId())){
                msg = "中断入包，白名单存在相关记录！";
                log.info(msg);
                return msg;
            }
        }else {
            //查询同商品包下是否存在同媒资节目
            prdContList = prdContService.getPrdContByMmsIdInPrdInfo(content.getAssetId(),prdInfo.getPrdInfoId());
            if(prdContList != null && prdContList.size() >0){
                msg = "中断入包，该商品包已存在同媒资节目！";
                log.info(msg);
                return msg;
            }
            //黑名单匹配
            if(filterBlack(content.getContentId(),Convert.toStr(prdInfo.getPrdInfoId()))){
                msg = "中断入包，黑名单存在相关记录！";
                log.info(msg);
                return msg;
            }
            //内容+商品包  白名单匹配
            if(filterWhiteByPrdInfoId(content.getContentId(),Convert.toStr(prdInfo.getPrdInfoId()))){
                msg = "中断入包，白名单存在相关记录！";
                log.info(msg);
                return msg;
            }
        }
        //商品包规则匹配
        if(!proInfoRuleManage.getWhichPrdInfo(content,prdInfo)){
            msg = "中断入包，该内容不符合该商品包规则！";
            log.info(msg);
            return msg;
        }
        return msg;
    }


    /**
     * <p><b>Title:</b> filterWhite</p>
     * <p><b>Description:</b> 移入日志判断修改为白名单</p>
     * @param contentId
     * @param prdInfoId
     * @return
     */
    private Boolean filterWhiteByPrdInfoId(String contentId, String prdInfoId) {
        ContentWhite params = new ContentWhite();
        params.setContentId(contentId);
        params.setPrdInfoId(Convert.toLong(prdInfoId));
        ContentWhite cw = contentWhiteService.findOne(params);
        if (cw == null) {
            return false;
        }
        return true;
    }

    /**
     * <p><b>Title:</b> filterWhite</p>
     * <p><b>Description:</b> 移入日志判断修改为白名单</p>
     * @param contentId
     * @param pip
     * @return
     */
    private Boolean filterWhiteByPip(String contentId, Long pip) {
        ContentWhite params = new ContentWhite();
        params.setContentId(contentId);
        params.setPackageId(Convert.toLong(pip));
        ContentWhite cw = contentWhiteService.findOne(params);
        if (cw == null) {
            return false;
        }
        return true;
    }

    /**
     * <p><b>Title:</b> filterBlack</p>
     * <p><b>Description:</b> 通过商品包过滤黑名单</p>
     * @param contentId
     * @param prdInfoId
     * @return
     */
    private Boolean filterBlack(String contentId, String prdInfoId) {
        ContentBlack params = new ContentBlack();
        params.setContentId(contentId);
        params.setPrdInfoId(Convert.toLong(prdInfoId));
        List<ContentBlack> cbs = contentBlackService.findAll(params);
        if(cbs != null && cbs.size()>0){
            return true;
        }
        return false;
    }

    /**
     * <p><b>Title:</b> initPrdCont</p>
     * <p><b>Description:</b> 新增时初始化节目对象</p>
     *
     * @param c
     * @param prdInfo
     * @return
     * @author douzi
     */
    public PrdCont initPrdCont(Content c, PrdInfo prdInfo) {

        PrdCont pc = new PrdCont();
        pc.setPrdInfoId(prdInfo.getPrdInfoId());
        pc.setContentId(c.getContentId());
        pc.setMmsId(Long.parseLong(c.getAssetId()));
        pc.setCopyRightObjectID(Long.parseLong(c.getCopyrightObjectId()));
        pc.setBcStatus(Constants.BC_STATUS_0);
        pc.setBcId(null);
        pc.setPubStatus(Constants.PUB_STATUS_10);
        pc.setFileAction(NumberUtils.toInt(c.getStatus() + ""));
        pc.setFormType(c.getFormType());
        pc.setIsEmergency(c.getBcPriority());
        pc.setLongtitle(c.getName());
        pc.setShorttitle(c.getShortName());
        pc.setIsShowPrdId("1");
        pc.setPrice(c.getPricing());
        pc.setPublishNoVOMSStatus(Constants.PRD_CONT_PUBLISH_STATUS_10);

        /** 保留字段开始，无用 */
        pc.setDistStatus(Constants.DISTON_STATUS_10);
        pc.setRecall(Constants.RECALL_STATUS_0);
        pc.setIsEmergency(Constants.EMERGENCY_0);
        if (StringUtils.isNotBlank(c.getBcId())) {
            try {
                pc.setBcId(Long.valueOf(c.getBcId().trim()));
            } catch (Exception e) {
            }
        }
        /** 保留字段结束，无用 */
        if ((c.getFormType() != null && c.getFormType().trim().equals("6"))
                || (c.getCategory() != null && c.getCategory().trim().equals("3"))) {
            pc.setDistStatus(Constants.DISTON_STATUS_12);
        }

        if (c.getHasVideo() != null && (c.getHasVideo()).equals(0)) {// 兼容媒资
            pc.setDistStatus(Constants.DISTON_STATUS_12);
        }

        PrdCont.putTimeAndUser(pc);
//        //保证节目id唯一 高正行待验证
//        Long productInfoPackageId=prdInfoDao.findProductInfoPackageId(2,prdInfo.getPrdInfoId());
//        //没有二级产品的产品(商品)包
//        if(productInfoPackageId==null || 0L==productInfoPackageId){
//            List<PrdCont> onList=prdContDao.findPcByContentIdInPrdInfo(c.getContentId(),prdInfo.getPrdInfoId());
//            if(onList.size()>0){
//                pc.setPrdContId(onList.get(0).getPrdContId());
//                if(onList.size()>1){
//                    onList.remove(0);
//                    delListPrdCont(onList);
//                }
//            }else {
//                List<PrdCont> delList=prdContDao.findAllPcByContentIdInPrdInfo(c.getContentId(),prdInfo.getPrdInfoId());
//                if(delList.size()>0){
//                    pc.setPrdContId(delList.get(0).getPrdContId());
//                }
//            }
//        }
//        //有二级产品的产品(商品)包
//        else{
//            List<PrdCont> onList=prdContDao.findPcByContentIdInPackageId2(c.getContentId(),productInfoPackageId);
//            if(onList.size()>0){
//                pc.setPrdContId(onList.get(0).getPrdContId());
//                if(onList.size()>1){
//                    onList.remove(0);
//                    delListPrdCont(onList);
//                }
//            }else {
//                List<PrdCont> delList=prdContDao.findAllPcByContentIdInPackageId2(c.getContentId(),productInfoPackageId);
//                if(delList.size()>0){
//                    pc.setPrdContId(delList.get(0).getPrdContId());
//                }
//            }
//        }

        log.info("主流程|媒资ID:" + c.getAssetId() + "|内容:" + c.getContentId() + "|入包二级产品:" + prdInfo.getProductInfoPackageId() + "|初始化节目对象:" + pc.toString());
        return pc;
    }




    /**
     * <p><b>Title:</b> subSetToNewPrdInfo</p>
     * <p><b>Description:</b> 如果是壳，需要让子集跟着一起去新包</p>
     *
     * @param newPrdInfoId
     * @param prdContDbs
     * @param
     * @author douzi
     */
    public void subSetToNewPrdInfo(Long newPrdInfoId, List<PrdCont> prdContDbs, Content c) {
        if (StringUtils.isNotBlank(c.getFormType())
                && (("6").equals(c.getFormType()) || ("10").equals(c.getFormType())
                || ("14").equals(c.getFormType()) || ("15").equals(c.getFormType()))) {
            if (prdContDbs.size() < 1) {
                log.info("主流程|子集跟随壳变更|DB中不存在壳的节目");
                return;
            }

            PrdCont pc = prdContDbs.get(0);
            if (newPrdInfoId.equals(pc.getPrdInfoId())) {
                log.info("主流程|子集跟随壳变更|壳的包没有变更");
                return;
            }

            List<PrdCont> subPrdConts = prdContService.getSerialsAllPublish(pc.getPrdInfoId(), pc.getMmsId());
            if (CollectionUtils.isEmpty(subPrdConts)) {
                log.info("主流程|子集跟随壳变更|壳没有子集存在");
                return;
            }

            for (PrdCont subPc : subPrdConts) {
                // 走定时发布
                subPc.setPrdInfoId(newPrdInfoId);
                subPc.setPublishNoVOMSStatus(Constants.PRD_CONT_PUBLISH_STATUS_10);
                PrdCont.putTimeAndUser(subPc);
                prdContService.save(subPc);
            }
        }
    }

    /**
     * <p><b>Title:</b> prepareNotify</p>
     * <p><b>Description:</b> 根据先上后审、免审、先审后上 准备推送流程</p>
     *
     * @param
     * @param prdCont
     * @author douzi
     */
    public void prepareNotify(PrdInfo prdInfo, Content c, PrdCont prdCont) {
        log.info("主流程|媒资ID:" + c.getAssetId() + "|superBcType:" + c.getSuperBcType());
        if (c.getSuperBcType() == null) {
            c.setSuperBcType(Constants.SUPER_BC_TYPE_2);
        }
        switch (c.getSuperBcType()) {
            case Constants.SUPER_BC_TYPE_1:
                outHttpUtil.online(prdCont);
                notifyBcManager.process(prdInfo, c, prdCont);
                break;
            case Constants.SUPER_BC_TYPE_0:
            case Constants.SUPER_BC_TYPE_2:
                notifyBcManager.process(prdInfo, c, prdCont);
                break;
            case Constants.SUPER_BC_TYPE_3:
                innerBc(prdCont);
                outHttpUtil.online(prdCont);
                // if big screen, must broadcast control
//                ProductInfoPackage pip = productInfoPackageService.get(prdInfo.getProductInfoPackageId());
//                if (pip != null) {
//                    if (pip.getProductInfoPackageType() == 1) {
//                        notifyBcManager.process(prdInfo, c, prdCont);
//                    }
//                } else {
//                }
                break;
            default:
                log.info("媒资:" + c.getAssetId() + "|内容:" + c.getContentId() + "|不属于任何一种流程标记（先上后审、免审、先审后上）：" + c.getSuperBcType());
                break;
        }
    }

    /**
     * <p><b>Title:</b> innerBc</p>
     * <p><b>Description:</b> 内部播控修改状态</p>
     *
     * @param pc
     * @author douzi
     */
    void innerBc(PrdCont pc) {
        pc.setBcStatus(Constants.BC_STATUS_1);
        pc.setBcTime(new Date());
        pc.setBcPerson("INNER_BC");
        pc.setPublishNoVOMSStatus(Constants.PUB_STATUS_10);
        PrdCont.putTimeAndUser(pc);
        prdContService.save(pc);
    }

    /**
     * <p><b>Title:</b> innerBc</p>
     * <p><b>Description:</b> 修改节目状态定时删除节目</p>
     *
     * @param list
     * @author douzi
     */
    void delListPrdCont(List<PrdCont> list) {
        for (PrdCont prdCont:list) {
            prdCont.setPublishNoVOMSStatus(Constants.PRD_CONT_PUBLISH_STATUS_20);
            PrdCont.putTimeAndUser(prdCont);
            prdContService.save(prdCont);
        }
    }

}

